package com.cipta.lomob;

import java.util.Arrays;

import org.json.JSONObject;

import tv.lomob.api.Lomob;
import tv.lomob.api.LomobResponseHandler;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cipta.lomob.base.BaseActivity;
import com.cipta.lomob.components.LomobFBLoginButton;
import com.cipta.lomob.utils.StringFormatter;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;

public class RegisterActivity extends BaseActivity{
	private TextView txtLogin;
	private Button btnTwitter;
	private LomobFBLoginButton btnFacebook;
	private UiLifecycleHelper uiHelper;
	private JSONObject userObject;
	private ProgressBar progressBar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		
	    //prepare facebook routine
        uiHelper = new UiLifecycleHelper(this, new Session.StatusCallback() {
			
			@Override
			public void call(Session session, SessionState state, Exception exception) {
				if(session.isOpened() && state == SessionState.OPENED){
 
				}
			}
		});
        uiHelper.onCreate(savedInstanceState);
		
		initializeViews();
		initializeProcess();
		initializeActions();
	}
	
	@Override
	public void initializeViews() {
		// TODO Auto-generated method stub
		super.initializeViews();
		txtLogin = (TextView)findViewById(R.id.txt_register_login);
		btnFacebook = (LomobFBLoginButton) findViewById(R.id.btn_register_fb);
		btnTwitter = (Button)findViewById(R.id.btn_register_twitter);		
	}
	
	@Override
	public void initializeProcess() {
		// TODO Auto-generated method stub
		super.initializeProcess();
		
		String strLogin = "Login now";
		txtLogin.setText(strLogin);
		txtLogin.setTextColor(getResources().getColor(R.color.comand_text_color));
		btnFacebook.setReadPermissions(Arrays.asList("email", "public_profile", "user_birthday", "user_friends", "read_friendlists"));
	}
	
	@Override
	public void initializeActions() {
		// TODO Auto-generated method stub
		super.initializeActions();
		txtLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				LoginActivity.toLoginActivity(RegisterActivity.this);
				finish();
			}
		});
		
//		btnFacebook.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				SignupActivity.toSignupActivity(RegisterActivity.this);
//			}
//		});
		
		btnFacebook.setUserInfoChangedCallback(new LomobFBLoginButton.UserInfoChangedCallback() {
			
			@Override
			public void onUserInfoFetched(GraphUser user) {
				//now got user profile
				if(user !=null){
					Log.i("Facebook", "logged as " + user.getFirstName());
					try{
						userObject = new JSONObject();
						userObject.put("facebook_id", user.getId());
						userObject.put("firstname", user.getFirstName());
						userObject.put("lastname", user.getLastName());
						userObject.put("username", user.asMap().get("email"));
						userObject.put("gender", user.asMap().get("gender"));						
						userObject.put("avatar", "https://graph.facebook.com/"+user.getId()+"/picture?height=200&type=normal&width=200");	
						userObject.put("token_fb", Session.getActiveSession().getAccessToken());
						
						//convert facebook birthday format
						String birthday = StringFormatter.converToDateFormat(user.getBirthday());
						userObject.put("birthday", birthday);
						
						//now check if user exist
						Lomob.isRegistered(userObject, new LomobResponseHandler() {
							
							@Override
							public void onSuccess(JSONObject result) {
								try{
									boolean isRegistered = result.optBoolean("isregistered");
//									if(!isRegistered){
									//for testing
									if(!isRegistered){
										//set user to lomob manager
										LomobManager.getInstance().setUser(RegisterActivity.this,userObject);						
										SignupActivity.toSignupActivity(RegisterActivity.this);
									}else{
										//user was registered so clear facebook session
										Session.getActiveSession().closeAndClearTokenInformation();
										LomobManager.getInstance().showDialog(RegisterActivity.this, "You was registered! Please login to access your account.");
									}
								}catch(Exception ex){
									ex.printStackTrace();
								}
							}
							
							@Override
							public void onError(String message) {
								LomobManager.getInstance().showDialog(RegisterActivity.this, message);
							}
						});

					}catch(Exception ex){
						ex.printStackTrace();
					}
				}
			}
		});

		btnTwitter.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				SignupActivity.toSignupActivity(RegisterActivity.this);
			}
		});
	}
	
	
	
	public static void toRegisterActivity(Activity activity){
		activity.startActivity(new Intent(activity, RegisterActivity.class));
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	  super.onActivityResult(requestCode, resultCode, data);
	  uiHelper.onActivityResult(requestCode, resultCode, data);
	}
}
